import React, { Fragment } from 'react';
import {
  DownOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Row,
  Col,
  Select,
  Input,
  Button,
  Badge,
  Alert,
  Modal,
  DatePicker,
  Tabs,
  Menu,
  Dropdown,
  Divider,
  message,
  Spin,
  Tooltip,
  Form,
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import queryString from 'query-string';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile, { formatNumber } from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import Customer from '../../components/Customer';
import TaskProgress from '../../components/TaskProgress';
import Contract from '../../components/ContractWithState';
import TextOverFlow from '../../components/TextOverFlow';

const { Option } = Select;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const { TabPane } = Tabs;
const { confirm } = Modal;

let uploadFiles = null;

@connect(({ customerbilling, loading, publicdata }) => ({
  customerbilling,
  data: customerbilling.data,
  activeKey: customerbilling.activeKey,
  dictCode: publicdata.dictCode,
  pageData: customerbilling.data,
  formFieldsValue: customerbilling.formFieldsValue,
  loading:
    loading.models.customerbilling &&
    !loading.effects['customerbilling/getProgress'] && // 进度接口
    !loading.effects['customerbilling/updateCheckCreate'] && // 生成账单接口
    !loading.effects['customerbilling/uploadFileWithProgress'] &&
    !loading.effects['customerbilling/markModelData'] && // 标记已收费的接口
    !loading.effects['customerbilling/getCustName'], // 生成账单查询客户接口
  signLoading: loading.effects['customerbilling/markModelData'], // 标记已收费的loading
  fetching: loading.effects['customerbilling/getCustName'], // 生成账单查询客户的loading
  expandForm: customerbilling.expandForm,
  respUserList: customerbilling.respUserList,
}))
class BillingList extends React.Component {
  formRef = React.createRef();

  state = {
    statusMap: ['', 'default', 'processing', 'warning', 'success'],
    selectedRowKeys: [],
    selectedRows: [],
    CUST_BILL_STATE: [],
    times: moment(new Date()).format('YYYY-MM-DD'),
    custList: [{ custId: 'CUST_ALL', name: '全部' }],
    cusName: '', // 生成账单 - 选择客户
    yearDay: '', // 截止年月
    sumPrice: 0, // 选择的总钱数
    isSign: false, // 标记已收费完成时提示弹框显隐
    btnLoding: false,
    exportLoding: false,
  };

  // 组件dom渲染完成
  componentDidMount() {
    this.checkHasTask();
    const {
      pageData: { pagination },
      location,
      dispatch,
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const { queryParam } = location;
    const tempActiveKey = queryString.parse(location.search).activeKey || '1';
    // 获取所属客服列表数据
    dispatch({
      type: 'customerbilling/fetchRespUserList',
      payload: {},
    });
    dispatch({
      type: 'customerbillcs/updateModelData',
      payload: {
        formFieldsValue: { defaultFlag: '1' },
        progressPercent: 0,
      },
    });

    if (isMenuLink === 'true') {
      this.resetAndGeLlist(location);
    } else if (isMenuLink === 'false') {
      if (queryParam) {
        if (queryParam.name) {
          dispatch({
            type: 'publicdata/getCustList',
            payload: [{ custId: queryParam.custId, name: queryParam.name }],
          });
          this.formRef.current.setFieldsValue({ custId: queryParam.custId });
        }
        dispatch({
          type: 'customerbilling/updateModelData',
          payload: {
            formFieldsValue: queryParam,
            expandForm: true,
          },
        });
      }
      this.getList(tempActiveKey, pagination.current, pagination.pageSize, queryParam);
    } else {
      this.getList(tempActiveKey, pagination.current, pagination.pageSize);
    }

    this.formRef.current.resetFields(['custIds', 'billYmModal']);
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['CUST_BILL_STATE'],
    }).then(data => {
      let taskSourceList = [];
      if (data && data.CUST_BILL_STATE && data.CUST_BILL_STATE.length) {
        taskSourceList = data.CUST_BILL_STATE;
      }
      this.setState({ CUST_BILL_STATE: taskSourceList });
    });
  }

  componentWillUnmount() {
    this.formRef.current.resetFields(['custIds', 'billYmModal']);
    window.clearInterval(uploadFiles);
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'customerbilling/checkCreateBillTask',
    });
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const {
      activeKey,
      data: { pagination },
      dispatch,
    } = this.props;
    if (!flag) {
      dispatch({
        type: 'customerbilling/updateModelData',
        payload: {
          showProgress: false,
        },
      });
      this.getList(activeKey, pagination.current, pagination.pageSize);
    }
  };

  // 查询表格布局
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'customerbilling/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 获取列表
  getList = async (activeKey = '1', currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    if (isClear) {
      this.setState({
        sumPrice: 0,
        selectedRows: [],
        selectedRowKeys: [],
      });
    }

    const { dispatch } = this.props;
    try {
      const fieldsValue = await this.formRef.current.validateFields();
      const tempFieldsValue = queryParam || fieldsValue;
      delete tempFieldsValue.billYmModal;
      delete tempFieldsValue.custIds;
      dispatch({
        type: 'customerbilling/updateModelData',
        payload: { formFieldsValue: tempFieldsValue, activeKey },
      });
      const formFieldsValue = {};
      Object.keys(tempFieldsValue).forEach(key => {
        if (key === 'billNo') {
          tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
        }
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
        delete formFieldsValue.operTime;
      });

      const pageArg = { currentPage, pageSize };

      if (formFieldsValue.billYm && formFieldsValue.billYm != null) {
        formFieldsValue.billYm = formFieldsValue.billYm.format('YYYYMM');
      }
      if (activeKey === '2') {
        const values = {
          pageArg,
          ...formFieldsValue,
        };
        dispatch({
          type: 'customerbilling/getUnpaidBillsList',
          payload: values,
        });
      } else {
        const values = {
          ...formFieldsValue,
          pageArg,
        };
        dispatch({
          type: 'customerbilling/getListBill',
          payload: values,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 生成账单 - 选择客户
  getCusname = value => {
    this.setState({
      cusName: value,
    });
  };

  // 取消标记弹框
  closeUnmark = () => {
    this.setState({
      isSign: false,
    });
  };

  // 标记已收费
  submark = () => {
    const { selectedRowKeys } = this.state;
    const {
      pageData: { pagination },
      dispatch,
      activeKey,
    } = this.props;
    dispatch({
      type: 'customerbilling/markModelData',
      payload: { billIdList: selectedRowKeys },
      callback: res => {
        if (res.success) {
          if (+res.data.errorCount === 0 && +res.data.successCount !== 0) {
            message.success('标记成功！');
            this.setState({
              selectedRowKeys: [],
              selectedRows: [],
              isSign: false,
              sumPrice: 0,
            });
            this.getList(activeKey, pagination.current, pagination.pageSize);
          }
        } else {
          this.setState({
            isSign: false,
          });
          message.warning(res.message || '标记失败：服务端未知错误');
        }
      },
    });
  };

  // 标记成功的关闭
  handleCancel = () => {
    const {
      activeKey,
      data: { pagination },
    } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize);
  };

  // 截止年月
  yearDay = e => {
    this.setState({
      yearDay: e.format('YYYYMM'),
    });
  };

  // 拆单
  billingSplit = record => {
    router.push(`/chargemanage/customerbilling/billingsplit?billYm=${record.billId}`);
  };

  // 列表搜索
  searchList = async activeKey => {
    const { dispatch } = this.props;
    try {
      const values = await this.formRef.current.validateFields([
        'billNo',
        'billState',
        'billYm',
        'custId',
        'contId',
      ]);
      dispatch({
        type: 'customerbilling/updateModelData',
        payload: { formFieldsValue: values, activeKey },
      });
      this.setState({ sumPrice: 0, selectedRowKeys: [], selectedRows: [] }, () => {
        this.getList(activeKey, 1, 10);
      });
    } catch (error) {
      console.error(error);
    }
  };

  // 查询合同
  getDatathree = (selectValue, options) => {
    if (options) {
      this.formRef.current.setFieldsValue({ contId: options });
    }
  };

  // 客户信息的客户名称
  searchName = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      this.setState({ custList: [] });
      dispatch({
        type: 'customerbilling/getCustName',
        payload: { name: value },
        callback: res => {
          if (res.success && res.data) {
            res.data.splice(0, 0, { custId: 'CUST_ALL', name: '全部' });
            this.setState({ custList: res.data });
          } else {
            message.warning(res.message || '查询失败');
          }
        },
      });
    } else {
      this.setState({ custList: [] });
    }
  };

  // 重置
  handleFormReset = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'customerbilling/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue({ billYm: null });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, undefined, false);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    const sumPrice = selectedRows.reduce(
      (total, currentValue) => total + currentValue.billAmo || 0,
      0
    );
    this.setState({ sumPrice, selectedRows, selectedRowKeys });
  };

  // 切换模态框：新增、修改
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields(['custIds', 'billYmModal']);
    this.yearDay(moment());
    dispatch({
      type: 'customerbilling/updateModelData',
      payload: { modalVisible: !!flag },
    });
  };

  // 提交生成账单信息
  submitData = async () => {
    const { dispatch } = this.props;
    const { cusName, yearDay } = this.state;
    const pldata = {
      custId: cusName,
      billYm: yearDay,
    };
    try {
      await this.formRef.current.validateFields(['custIds', 'billYmModal']);
      this.setState({
        btnLoding: true,
      });
      dispatch({
        type: 'customerbilling/updateCheckCreate',
        payload: pldata,
        callback: response => {
          if (response.success && +response.data === 0) {
            dispatch({
              type: 'customerbilling/uploadFileWithProgress',
              payload: { batchType: 1, params: pldata },
            }).then(res => {
              if (res.success && res.data.taskCode && res.data.successProp !== 100) {
                this.setState({ btnLoding: false });
              }
            });
          } else {
            this.setState({ btnLoding: false });
            message.warning('当前客户已生成过选择月份账单，增量数据请到未进账单页面生成!');
          }
        },
      });
    } catch (error) {
      console.error(error);
    }
  };

  // 下载
  export = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      message.warning('请至少选择一条账单数据');
    } else {
      this.setState({
        exportLoding: true,
      });
      this.exportExcel(singleOrMerge);
    }
  };

  // 导出excel
  exportExcel = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    const params = {
      billIdList: selectedRowKeys,
    };
    const { dispatch } = this.props;
    dispatch({
      type:
        singleOrMerge === 'downSingleBillDet'
          ? 'customerbillcs/singleExport'
          : 'customerbillcs/mergeExport',
      payload: params,
    }).then(res => {
      if (res.success) {
        uploadFiles = setInterval(() => {
          dispatch({
            type: 'customerbillcs/uploadFile',
            payload: { billKey: res.data, downType: singleOrMerge === 'downSingleBillDet' ? 2 : 3 },
          }).then(resFile => {
            if (resFile.success) {
              if (resFile.success && resFile.data && resFile.data.fileId && resFile.data.fileName) {
                window.clearInterval(uploadFiles);
                downloadFile(
                  { fileId: resFile.data.fileId, fileName: resFile.data.fileName },
                  '/csApi/fileServer/downloadFile',
                  'GET',
                  () => {
                    this.setState({
                      exportLoding: false,
                    });
                  }
                );
              }
            } else {
              message.warning(resFile.message || '下载失败');
              window.clearInterval(uploadFiles);
              this.setState({
                exportLoding: false,
              });
            }
          });
        }, 2000);
      } else {
        this.setState({
          exportLoding: false,
        });
        window.clearInterval(uploadFiles);
        message.warning(res.message || '下载失败');
      }
    });
  };

  // 查看详情
  toDetail = record => {
    router.push(`/chargemanage/customerbilling/detail?billId=${record.billId}`);
  };

  toBillDetail = record => {
    router.push(
      `/chargemanage/customerbilling/tobilllist?custId=${record.custId}&billYm=${
        record.billYm
      }&See=${1}&contId=${record.contId}&tabpaneid=2`
    );
  };

  // 合并
  mergeMeony = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'customerbilling/checkCreateBillTask',
    }).then(response => {
      if (response.success) {
        if (response.data && response.data.taskCode === 3) {
          message.warning('当前有账单任务正在生成，请稍后操作！');
          return false;
        }
        if (that.state.selectedRowKeys.length >= 2) {
          confirm({
            icon: <QuestionCircleOutlined />,
            title: '你确定要合并吗?',
            okText: '合并',
            okType: 'default',
            cancelText: '取消',
            style: { top: 200 },
            onOk: () => {
              dispatch({
                type: 'customerbilling/uploadFileWithProgress',
                payload: { batchType: 2, params: { billIdList: selectedRowKeys } },
              });
            },
          });
        } else {
          message.warning('请至少选择两条账单数据');
        }
      } else {
        message.warning(response.message || '服务端未知错误');
      }
      return true;
    });
  };

  // 删除账单
  deleteBill = () => {
    const {
      dispatch,
      data: {
        pagination: { current, pageSize, total },
      },
    } = this.props;
    const { selectedRowKeys, selectedRows, CUST_BILL_STATE } = this.state;
    if (selectedRowKeys.length) {
      const iaDisable = selectedRows.some(row => row.billState !== 1);
      if (iaDisable) {
        const idList = [];
        const filterRows = selectedRows.filter(item => item.billState !== 1);
        filterRows.forEach(r => {
          CUST_BILL_STATE.forEach(c => {
            if (c.itemCode === `${r.billState}`) {
              idList.push(r.billNo);
            }
          });
        });
        return message.warning(
          `账单编号${idList.length > 1 ? '分别' : ''}为“${idList.join(
            '、'
          )}”的账单不允许删除，只能针对状态为“待收费”的账单操作删除!`
        );
      }
      const billNoList = [];
      selectedRows.forEach(item => {
        billNoList.push(item.billNo);
      });
      confirm({
        icon: <QuestionCircleOutlined />,
        title: `你确定要删除编号为“${billNoList.join('、')}”的账单吗?`,
        content: (
          <div>
            <span>注意：</span>
            <span>
              当月账单全部删除后，需要重新操作生成账单；
              <br />
              <span style={{ opacity: 0 }}>注意：</span>
              当月账单部分删除后，被删除的数据会进入到【未进账单数据】中。
            </span>
          </div>
        ),
        okText: '删除',
        cancelText: '取消',
        width: 570,
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'customerbilling/deleteBill',
            payload: { billIdList: selectedRowKeys },
          }).then(res => {
            if (res.success) {
              const selectedLen = 1;
              if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                this.getList('1', current - 1, pageSize);
              } else {
                this.getList('1', current, pageSize);
              }
              this.setState({ selectedRowKeys: [], selectedRows: [], sumPrice: 0 });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败'}`);
            }
          });
        },
        onCancel: () => {
          this.setState({ selectedRowKeys: [], sumPrice: 0 });
        },
      });
    } else {
      message.warning('请至少选择一条账单数据');
    }
    return true;
  };

  // 标记已收费
  markCharged = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择数据进行操作！');
      return;
    }
    const selectKey = [];
    let billType = null;
    const billNoList = [];
    selectedRows.map(item => {
      selectKey.push({ billState: item.billState, billNo: item.billNo });
      return true;
    });
    selectKey.map(items => {
      if (items.billState === 1) {
        billType = 1;
      } else {
        billType = 2;
        billNoList.push(items.billNo);
      }
      return true;
    });
    if (billType === 1 && billNoList.length === 0) {
      this.setState({
        isSign: true,
      });
    } else {
      message.warning(` 账单编号${billNoList.length > 1 ? '分别' : ''} 为 ${billNoList.join('、')}
      的账单不允许标记，只能针对状态为“待收费”的账单操作标记收费！`);
      this.setState({
        isSign: false,
      });
    }
  };

  // 切换页签
  async changeTabPane(activeKey) {
    const { dispatch } = this.props;
    router.push(`/chargemanage/customerbilling/index?activeKey=${activeKey}`);
    await dispatch({
      type: 'customerbilling/updateModelData',
      payload: {
        activeKey,
        formFieldsValue: {},
      },
    });
    await dispatch({
      type: 'publicdata/updateModelData',
      payload: { custList: [], custFsValue: { title: undefined } },
    });
    await this.handleFormReset();
    await this.getList(activeKey);
  }

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    dispatch({
      type: 'customerbilling/updateModelData',
      payload: { expandForm: false, activeKey: '1' },
    });
    await this.handleFormReset();
    await this.getList(location.query.activeKey);
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const {
      customerbilling,
      data,
      activeKey,
      formFieldsValue,
      loading,
      signLoading,
      fetching,
      respUserList,
    } = this.props;
    const {
      statusMap,
      selectedRowKeys,
      custList,
      sumPrice,
      selectedRows,
      isSign,
      CUST_BILL_STATE,
      times,
      btnLoding,
      exportLoding,
    } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '账单年月',
        dataIndex: 'billYm',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单编号',
        dataIndex: 'billNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (text, record) => <span className="editable-row-operations">{record.billNo}</span>,
      },
      {
        title: '账单金额',
        dataIndex: 'billAmo',
        align: 'right',
        width: 130,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  涉及人数：
                  {record.involvePersonNum}
                </p>
                <p>{record.agtsrvIns ? `代收社保：${formatNumber(record.agtsrvIns)}` : ''}</p>
                <p>{record.agtsrvAccu ? `代收公积金：${formatNumber(record.agtsrvAccu)}` : ''}</p>
                <p>{record.agtsrvWage ? `代收工资：${formatNumber(record.agtsrvWage)}` : ''}</p>
                <p>{record.othCost ? `服务费：${formatNumber(record.othCost)}` : ''}</p>
                <p>{record.bnftAmo ? `福利费：${formatNumber(record.bnftAmo)}` : ''}</p>
                <p>{record.medExamAmo ? `体检费：${formatNumber(record.medExamAmo)}` : ''}</p>
                <p>{record.cmpinsAmo ? `保险：${formatNumber(record.cmpinsAmo)}` : ''}</p>
                <p>{record.riskAmo ? `风险金：${formatNumber(record.riskAmo)}` : ''}</p>
              </div>
            }
          >
            {text ? (
              <span>
                {formatNumber(text)}
                <EllipsisOutlined style={{ fontSize: 14, color: '#08c' }} />
              </span>
            ) : (
              <span> {text === 0 ? 0 : '--'}</span>
            )}
          </Tooltip>
        ),
      },
      {
        title: '收费截止日期',
        dataIndex: 'lastFeeDate',
        width: 170,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (val, record) => (
          <div>
            {moment(val).format('YYYY-MM-DD')}
            {moment(val).format('YYYY-MM-DD') < times &&
              (record.billState === 1 || record.billState === 2) && (
                <span
                  style={{
                    marginTop: '1px',
                    marginLeft: '-10px',
                    border: '1px solid red',
                    width: '64px',
                    color: 'red',
                    borderRadius: '4px',
                    fontSize: '16px',
                    WebkitTextSizeAdjust: 'none',
                    display: 'inline-block',
                    transform: 'scale(0.5)',
                    textAlign: 'center',
                  }}
                >
                  已逾期
                </span>
              )}
          </div>
        ),
      },
      {
        title: '商务合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '成本中心',
        dataIndex: 'costCenterName',
        align: 'left',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '账单状态',
        dataIndex: 'billState',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (val, record) => <Badge status={statusMap[val]} text={record.billStateName} />,
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        align: 'left',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '操作',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() => {
                this.toDetail(record);
              }}
            >
              查看
            </a>
            {checkPermissions('cs:csBill:split') && record.involvePersonNum > 1 && (
              <Divider type="vertical" />
            )}
            {checkPermissions('cs:csBill:split') && record.involvePersonNum > 1 && (
              <a key="update" onClick={() => this.billingSplit(record)}>
                拆分
              </a>
            )}
          </span>
        ),
      },
    ];

    const formItemLayoutModal = {
      labelCol: { md: { span: 5 } },
      wrapperCol: { md: { span: 17, offset: 1 } },
    };

    const moreMenu = (
      <Menu>
        {checkPermissions('cs:csBill:merge') && (
          <Menu.Item onClick={this.mergeMeony}>合并</Menu.Item>
        )}
        {checkPermissions('cs:csBill:deleteBill') && (
          <Menu.Item onClick={this.deleteBill}>删除</Menu.Item>
        )}

        {checkPermissions('cs:csBill:updateChrgState') && (
          <Menu.Item key="charged" onClick={() => this.markCharged()}>
            标记已收费
          </Menu.Item>
        )}
      </Menu>
    );
    const billingDownload = (
      <Menu>
        {checkPermissions('cs:csBill:downBillDet') && (
          <Menu.Item key="1" onClick={() => this.export('downSingleBillDet')}>
            单个下载
          </Menu.Item>
        )}
        {checkPermissions('cs:csBill:downBill') && (
          <Menu.Item key="2" onClick={() => this.export('downMergeBillDet')}>
            合并下载
          </Menu.Item>
        )}
      </Menu>
    );
    const columnsbill = [
      {
        title: '客户',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '商务合同',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单年月',
        dataIndex: 'billYm',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '金额',
        dataIndex: 'billAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: billAmo => formatNumber(billAmo) || (billAmo === 0 ? 0 : '--'),
      },

      {
        title: '符合条件人数',
        dataIndex: 'involvePersonNum',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: value => value || (value === 0 ? 0 : '--'),
      },
      {
        title: '不符合条件人数',
        dataIndex: 'unnaturalNum',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: value => value || (value === 0 ? 0 : '--'),
      },
      {
        title: '操作',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() => {
                this.toBillDetail(record);
              }}
            >
              查看
            </a>
            {checkPermissions('cs:csBill:createBill') && <Divider type="vertical" />}
            {checkPermissions('cs:csBill:createBill') && (
              <a
                key="update"
                onClick={() =>
                  router.push(
                    `/chargemanage/customerbilling/tobilllist?custId=${record.custId}&billYm=${
                      record.billYm
                    }&contId=${record.contId}&tabpaneid=2`
                  )
                }
              >
                生成账单
              </a>
            )}
          </span>
        ),
      },
    ];

    const renderSimpleForm = (
      <>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem name="custId" label="客户名称" {...formItemLayout}>
              <Customer allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem name="contId" {...formItemLayout} label="商务合同名称">
              <Contract getData={this.getDatathree} allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.getList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </>
    );
    const renderAdvancedForm = (
      <>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} name="custId" label="客户名称">
              <Customer allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} name="contId" label="商务合同名称">
              <Contract getData={this.getDatathree} allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账单年月" name="billYm" {...formItemLayout}>
              <MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem {...formItemLayout} name="billState" label="账单状态">
                <Select placeholder="请选择" allowClear>
                  {CUST_BILL_STATE.map(item => (
                    <Option key={item.itemCode} value={item.itemCode}>
                      {item.itemName}
                    </Option>
                  ))}
                </Select>
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem {...formItemLayout} name="billNo" label="账单编号">
                <Input placeholder="请输入账单编号" />
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
          {activeKey === '1' ? (
            <Col md={8} sm={24}>
              <FormItem label="所属客服" name="primId" {...formItemLayout}>
                <Select
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {respUserList.map(item => (
                    <Option key={item.userId} title={item.userName}>
                      {item.userName}
                    </Option>
                  ))}
                </Select>
              </FormItem>
            </Col>
          ) : (
            <Col md={8} sm={24} />
          )}
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.getList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </>
    );
    const { expandForm, dispatch } = this.props;
    const renderForm = expandForm ? renderAdvancedForm : renderSimpleForm;
    return (
      <PageHeaderWrapper>
        <Spin spinning={exportLoding || loading}>
          <Card className={styles.tabCard}>
            <Form ref={this.formRef} initialValues={formFieldsValue}>
              <Tabs activeKey={activeKey} onChange={key => this.changeTabPane(key)}>
                <TabPane tab="账单" key="1">
                  <div
                    className={styles.tableListForm}
                    style={{
                      padding: '24px 24px 0 0',
                      backgroundColor: '#fafafa',
                    }}
                  >
                    {renderForm}
                  </div>
                  <Row gutter={32} style={{ marginTop: '16px', marginLeft: 0 }}>
                    <Authorized authority="cs:csBill:createBill" noMatch={null}>
                      <Button
                        style={{ marginRight: 8 }}
                        type="primary"
                        onClick={() => this.handleModalVisible(true)}
                      >
                        生成账单
                      </Button>
                    </Authorized>
                    <Dropdown overlay={billingDownload}>
                      <Button>账单下载</Button>
                    </Dropdown>
                    <Dropdown overlay={moreMenu}>
                      <Button style={{ marginLeft: 8 }}>
                        更多 <DownOutlined />
                      </Button>
                    </Dropdown>
                  </Row>
                  {customerbilling.isHasTask ? (
                    <Alert
                      style={{ margin: '16px 0 15px 0' }}
                      message={
                        <span>
                          您有正在生成账单的任务
                          <a
                            style={{ marginLeft: 20 }}
                            onClick={() => {
                              dispatch({
                                type: 'customerbilling/updateModelData',
                                payload: {
                                  showProgress: true,
                                },
                              });
                            }}
                          >
                            查看
                          </a>
                        </span>
                      }
                      type="warning"
                      showIcon
                    />
                  ) : (
                    <Alert
                      style={{ margin: '16px 0 15px 0' }}
                      message={
                        <Fragment>
                          已选择{' '}
                          <span style={{ color: '#088FEA' }}> {selectedRowKeys.length} </span>项
                          &nbsp; 总计： &nbsp;
                          <span style={{ fontWeight: 'bold' }}>
                            {sumPrice ? sumPrice.toFixed(2) : 0}
                          </span>
                          &nbsp;元
                        </Fragment>
                      }
                      type="info"
                      showIcon
                    />
                  )}
                  <StandardTable
                    selectedRows={selectedRows}
                    selectedRowKeys={selectedRowKeys}
                    data={data}
                    rowKey="billId"
                    columns={columns}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                  />
                  <Modal
                    title="生成账单"
                    visible={customerbilling.modalVisible}
                    onOk={() => this.submitData()}
                    onCancel={() => this.handleModalVisible(false)}
                    confirmLoading={btnLoding}
                    destroyOnClose
                    width="550px"
                  >
                    <Form ref={this.formRef} initialValues={{ billYmModal: moment() }}>
                      <FormItem
                        label={
                          <Tooltip title="可以选择全部，也可输入客户名称生成账单">
                            客户 <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                          </Tooltip>
                        }
                        name="custIds"
                        rules={[{ required: customerbilling.modalVisible, message: '请输入' }]}
                        {...formItemLayoutModal}
                      >
                        <Select
                          placeholder="请输入关键字检索"
                          showSearch
                          showArrow={false}
                          style={{ width: '100%' }}
                          filterOption={false}
                          onSearch={this.searchName}
                          allowClear
                          onSelect={value => this.getCusname(value)}
                          notFoundContent={fetching ? <Spin size="small" /> : null}
                        >
                          {custList.map(item => (
                            <Option key={item.custId}>{item.name}</Option>
                          ))}
                        </Select>
                      </FormItem>
                      <FormItem
                        label="截止年月"
                        name="billYmModal"
                        rules={[{ required: true, message: '请选择' }]}
                        {...formItemLayoutModal}
                      >
                        <MonthPicker
                          placeholder="请选择"
                          onChange={this.yearDay}
                          disabledDate={current =>
                            current < moment().subtract(1, 'months') ||
                            current > moment().add(5, 'months')
                          }
                          style={{ width: '100%' }}
                        />
                      </FormItem>
                    </Form>
                    <p style={{ margin: '0 0 0 0', color: '#ccc' }}>
                      注：1. 客户当月首次生成账单通过此功能，再次生成在未进账单功能中生成；
                    </p>
                    <p style={{ padding: '0 0 0 29px', margin: '-1px 0 0 0', color: '#ccc' }}>
                      2. 选择客户时可输入全部，也可输入一个客户生成账单；
                    </p>
                    <p style={{ padding: '0 0 0 29px', color: '#ccc' }}>
                      3.
                      如公司约定账单是“当月生成当月即以前”，则账单中只包含业务年月是当月及以前的数据；如公司约定账单是“当月生成次月即以前”，则账单中只包含业务年月是次月及以前的数据。
                    </p>
                  </Modal>
                  <TaskProgress
                    progressVisible={customerbilling.showProgress}
                    progressPercent={customerbilling.progressPercent || 0}
                    isShowResult={customerbilling.progressPercent === 100}
                    resultInfo={customerbilling.resultInfo}
                    checkHasTask={this.checkHasTask}
                    handleProgressModalVisible={this.handleProgressModalVisible}
                  />
                </TabPane>
                <TabPane tab="未进账单数据" key="2">
                  <div
                    className={styles.tableListForm}
                    style={{
                      padding: '24px 24px 0 0',
                      backgroundColor: '#fafafa',
                      marginBottom: '16px',
                    }}
                  >
                    {renderForm}
                  </div>
                  <StandardTable
                    selectedRows={selectedRows}
                    selectedRowKeys={selectedRowKeys}
                    data={data}
                    rowKey="key"
                    columns={columnsbill}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                    rowSelection={null}
                  />
                </TabPane>
              </Tabs>
            </Form>
          </Card>
          <Modal
            visible={isSign}
            onOk={this.submark}
            onCancel={this.closeUnmark}
            closable={false}
            destroyOnClose
            width="450px"
            footer={[
              <Button key="back" onClick={this.closeUnmark}>
                取消
              </Button>,
              <Button key="submit" type="primary" onClick={this.submark} loading={signLoading}>
                确认
              </Button>,
            ]}
          >
            <div style={{ margin: '15px 15px 0 15px' }}>
              <ExclamationCircleOutlined
                style={{ fontWeight: 800, color: '#EEC900', fontSize: '20px' }}
              />
              <span style={{ fontSize: '18px', fontWeight: 800, margin: '20px 0 0 10px' }}>
                已选择{selectedRowKeys.length}条数据，是否确认全部标记已收费
              </span>
              <p style={{ color: '#A19095', margin: '10px 0 0 28px' }}>
                请线下和财务核实每笔费用款已到款，标记后不可取消标记。
              </p>
            </div>
          </Modal>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default BillingList;
